package com.zenithmind.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.utils.BeanCopyUtils;
import com.zenithmind.task.mapper.TaskFollowerMapper;
import com.zenithmind.task.pojo.entity.TaskFollower;
import com.zenithmind.task.pojo.query.TaskFollowerQuery;
import com.zenithmind.task.pojo.vo.TaskFollowerVO;
import com.zenithmind.task.service.TaskFollowerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务关注服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskFollowerServiceImpl extends ServiceImpl<TaskFollowerMapper, TaskFollower> implements TaskFollowerService {

    @Override
    public PageResult<TaskFollowerVO> getTaskFollowerPage(TaskFollowerQuery query, String userId) {
        Page<TaskFollower> page = query.toPage();

        LambdaQueryWrapper<TaskFollower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(query.getTaskId()), TaskFollower::getTaskId, query.getTaskId())
               .eq(StringUtils.hasText(query.getFollowerId()), TaskFollower::getFollowerId, query.getFollowerId())
               .eq(query.getFollowType() != null, TaskFollower::getFollowType, query.getFollowType())
               .eq(query.getStatus() != null, TaskFollower::getStatus, query.getStatus());

        // 时间范围查询
        if (query.getCreateTimeBegin() != null) {
            wrapper.ge(TaskFollower::getCreateTime, query.getCreateTimeBegin());
        }
        if (query.getCreateTimeEnd() != null) {
            wrapper.le(TaskFollower::getCreateTime, query.getCreateTimeEnd());
        }

        wrapper.orderByDesc(TaskFollower::getCreateTime);

        IPage<TaskFollower> result = page(page, wrapper);

        List<TaskFollowerVO> voList = result.getRecords().stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    public TaskFollowerVO getTaskFollowerById(String id, String userId) {
        TaskFollower taskFollower = getById(id);
        if (taskFollower == null) {
            throw new BusinessException("任务关注记录不存在");
        }
        
        return convertToVO(taskFollower);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTaskFollower(TaskFollower taskFollower, String userId) {
        // 检查是否已关注
        if (isFollowing(taskFollower.getTaskId(), taskFollower.getFollowerId())) {
            throw new BusinessException("已关注该任务");
        }

        // 设置默认值
        if (taskFollower.getStatus() == null) {
            taskFollower.setStatus(1); // 有效
        }
        if (taskFollower.getFollowType() == null) {
            taskFollower.setFollowType(1); // 主动关注
        }

        taskFollower.setFollowTime(LocalDateTime.now());

        boolean result = save(taskFollower);
        
        if (result) {
            log.info("用户 {} 创建任务关注: 任务ID={}, 关注者ID={}", userId, taskFollower.getTaskId(), taskFollower.getFollowerId());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTaskFollower(String id, String userId) {
        TaskFollower taskFollower = getById(id);
        if (taskFollower == null) {
            throw new BusinessException("任务关注记录不存在");
        }

        // 权限检查：只能删除自己的关注记录
        if (!taskFollower.getFollowerId().equals(userId)) {
            throw new BusinessException("无权限删除该关注记录");
        }

        boolean result = removeById(id);
        
        if (result) {
            log.info("用户 {} 删除任务关注: ID={}", userId, id);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean followTask(String taskId, String userId) {
        // 检查是否已关注
        if (isFollowing(taskId, userId)) {
            return true; // 已关注，直接返回成功
        }

        TaskFollower taskFollower = new TaskFollower();
        taskFollower.setTaskId(taskId);
        taskFollower.setFollowerId(userId);
        taskFollower.setFollowType(1); // 主动关注
        taskFollower.setStatus(1); // 有效
        taskFollower.setFollowTime(LocalDateTime.now());

        boolean result = save(taskFollower);
        
        if (result) {
            log.info("用户 {} 关注任务: 任务ID={}", userId, taskId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unfollowTask(String taskId, String userId) {
        LambdaQueryWrapper<TaskFollower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskFollower::getTaskId, taskId)
               .eq(TaskFollower::getFollowerId, userId)
               .eq(TaskFollower::getStatus, 1);

        TaskFollower taskFollower = getOne(wrapper);
        if (taskFollower == null) {
            return true; // 未关注，直接返回成功
        }

        boolean result = removeById(taskFollower.getId());
        
        if (result) {
            log.info("用户 {} 取消关注任务: 任务ID={}", userId, taskId);
        }
        
        return result;
    }

    @Override
    public Boolean isFollowing(String taskId, String userId) {
        LambdaQueryWrapper<TaskFollower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskFollower::getTaskId, taskId)
               .eq(TaskFollower::getFollowerId, userId)
               .eq(TaskFollower::getStatus, 1);

        return count(wrapper) > 0;
    }

    @Override
    public List<TaskFollowerVO> getTaskFollowers(String taskId, String userId) {
        LambdaQueryWrapper<TaskFollower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskFollower::getTaskId, taskId)
               .eq(TaskFollower::getStatus, 1)
               .orderByDesc(TaskFollower::getFollowTime);

        List<TaskFollower> followers = list(wrapper);
        
        return followers.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }

    @Override
    public PageResult<TaskFollowerVO> getUserFollowedTasks(String userId, Integer pageNum, Integer pageSize) {
        Page<TaskFollower> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<TaskFollower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskFollower::getFollowerId, userId)
               .eq(TaskFollower::getStatus, 1)
               .orderByDesc(TaskFollower::getFollowTime);

        IPage<TaskFollower> result = page(page, wrapper);

        List<TaskFollowerVO> voList = result.getRecords().stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchFollowTasks(List<String> taskIds, String userId) {
        for (String taskId : taskIds) {
            followTask(taskId, userId);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUnfollowTasks(List<String> taskIds, String userId) {
        for (String taskId : taskIds) {
            unfollowTask(taskId, userId);
        }
        return true;
    }

    /**
     * 转换为VO对象
     */
    private TaskFollowerVO convertToVO(TaskFollower taskFollower) {
        TaskFollowerVO vo = BeanCopyUtils.copyBean(taskFollower, TaskFollowerVO.class);
        
        // 设置关注类型文本
        vo.setFollowTypeText(getFollowTypeText(taskFollower.getFollowType()));
        
        // 设置状态文本
        vo.setStatusText(getStatusText(taskFollower.getStatus()));
        
        return vo;
    }

    /**
     * 获取关注类型文本
     */
    private String getFollowTypeText(Integer followType) {
        switch (followType) {
            case 1: return "主动关注";
            case 2: return "自动关注";
            case 3: return "被邀请关注";
            default: return "未知";
        }
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        switch (status) {
            case 1: return "有效";
            case 0: return "无效";
            default: return "未知";
        }
    }
}
